from datetime import datetime
from typing import List, Optional, Dict, Any
import uuid
import logging

from app.storage.json_storage import storage
from app.models.simple_schemas import SimpleTaskConfig, SimpleTaskInfo, TaskStatus, TaskListParams, PaginatedResponse

logger = logging.getLogger(__name__)

class SimpleJSONTaskService:
    """简化的JSON任务服务"""
    
    def create_task(self, config: SimpleTaskConfig) -> SimpleTaskInfo:
        """创建任务 - 简化版本"""
        try:
            task_data = {
                'name': config.name,
                'urls': config.urls,
                'description': config.description,
                'status': TaskStatus.PENDING.value,
                'result': None,
                'error_message': None
            }
            
            new_task = storage.create_task(task_data)
            
            # 记录日志
            storage.add_log({
                'message': f'任务创建: {new_task["name"]}',
                'task_id': new_task['id'],
                'level': 'info'
            })
            
            return self._dict_to_task_info(new_task)
            
        except Exception as e:
            logger.error(f"Create task error: {e}")
            raise
    
    def get_task(self, task_id: str) -> Optional[SimpleTaskInfo]:
        """获取任务详情"""
        try:
            task = storage.get_task_by_id(task_id)
            if not task:
                return None
            
            return self._dict_to_task_info(task)
            
        except Exception as e:
            logger.error(f"Get task error: {e}")
            return None
    
    def list_tasks(self, params: TaskListParams) -> PaginatedResponse:
        """获取任务列表 - 简化版本"""
        try:
            all_tasks = storage.get_tasks()
            
            # 状态过滤
            if params.status:
                all_tasks = [t for t in all_tasks if t.get('status') == params.status.value]
            
            # 关键词搜索
            if params.search:
                search_lower = params.search.lower()
                all_tasks = [
                    t for t in all_tasks 
                    if search_lower in t.get('name', '').lower() 
                    or search_lower in t.get('description', '').lower()
                ]
            
            # 排序（按创建时间倒序）
            all_tasks.sort(key=lambda x: x.get('created_at', ''), reverse=True)
            
            # 分页
            total = len(all_tasks)
            start = (params.page - 1) * params.size
            end = start + params.size
            tasks = all_tasks[start:end]
            
            # 转换为TaskInfo对象
            task_infos = [self._dict_to_task_info(task) for task in tasks]
            
            return PaginatedResponse(
                items=task_infos,
                total=total,
                page=params.page,
                size=params.size,
                pages=(total + params.size - 1) // params.size
            )
            
        except Exception as e:
            logger.error(f"List tasks error: {e}")
            raise
    
    def update_task(self, task_id: str, config: SimpleTaskConfig) -> Optional[SimpleTaskInfo]:
        """更新任务"""
        try:
            update_data = {
                'name': config.name,
                'urls': config.urls,
                'description': config.description,
                'updated_at': datetime.utcnow().isoformat()
            }
            
            updated_task = storage.update_task(task_id, update_data)
            if not updated_task:
                return None
            
            # 记录日志
            storage.add_log({
                'message': f'任务更新: {updated_task["name"]}',
                'task_id': task_id,
                'level': 'info'
            })
            
            return self._dict_to_task_info(updated_task)
            
        except Exception as e:
            logger.error(f"Update task error: {e}")
            return None
    
    def delete_task(self, task_id: str) -> bool:
        """删除任务"""
        try:
            task = storage.get_task_by_id(task_id)
            if not task:
                return False
            
            success = storage.delete_task(task_id)
            
            if success:
                # 记录日志
                storage.add_log({
                    'message': f'任务删除: {task["name"]}',
                    'task_id': task_id,
                    'level': 'info'
                })
            
            return success
            
        except Exception as e:
            logger.error(f"Delete task error: {e}")
            return False
    
    def start_task(self, task_id: str) -> bool:
        """启动任务 - 简化版本（模拟执行）"""
        try:
            task = storage.get_task_by_id(task_id)
            if not task:
                return False
            
            # 更新状态为运行中
            storage.update_task(task_id, {
                'status': TaskStatus.RUNNING.value,
                'updated_at': datetime.utcnow().isoformat()
            })
            
            # 记录日志
            storage.add_log({
                'message': f'任务启动: {task["name"]}',
                'task_id': task_id,
                'level': 'info'
            })
            
            # 这里可以添加实际的爬虫逻辑
            # 为了简化，我们直接模拟完成
            self._simulate_task_completion(task_id, task)
            
            return True
            
        except Exception as e:
            logger.error(f"Start task error: {e}")
            return False
    
    def stop_task(self, task_id: str) -> bool:
        """停止任务"""
        try:
            task = storage.get_task_by_id(task_id)
            if not task:
                return False
            
            # 更新状态为已取消
            storage.update_task(task_id, {
                'status': TaskStatus.CANCELLED.value,
                'updated_at': datetime.utcnow().isoformat()
            })
            
            # 记录日志
            storage.add_log({
                'message': f'任务停止: {task["name"]}',
                'task_id': task_id,
                'level': 'info'
            })
            
            return True
            
        except Exception as e:
            logger.error(f"Stop task error: {e}")
            return False
    
    def get_task_logs(self, task_id: str, limit: int = 100) -> List[Dict]:
        """获取任务日志"""
        try:
            logs = storage.get_logs(task_id=task_id, limit=limit)
            return logs
            
        except Exception as e:
            logger.error(f"Get task logs error: {e}")
            return []
    
    def _dict_to_task_info(self, task_dict: Dict) -> SimpleTaskInfo:
        """将字典转换为TaskInfo对象"""
        return SimpleTaskInfo(
            id=task_dict['id'],
            name=task_dict['name'],
            urls=task_dict['urls'],
            status=TaskStatus(task_dict.get('status', TaskStatus.PENDING.value)),
            description=task_dict.get('description'),
            created_at=datetime.fromisoformat(task_dict['created_at']),
            updated_at=datetime.fromisoformat(task_dict['updated_at']) if task_dict.get('updated_at') else None,
            result=task_dict.get('result'),
            error_message=task_dict.get('error_message')
        )
    
    def _simulate_task_completion(self, task_id: str, task: Dict):
        """模拟任务完成 - 简化版本"""
        try:
            # 模拟处理结果
            result = {
                'urls_processed': len(task['urls']),
                'success_count': len(task['urls']),
                'failed_count': 0,
                'data': [
                    {
                        'url': url,
                        'title': f'页面标题 - {url}',
                        'content': f'这是从 {url} 爬取的内容...',
                        'status': 'success'
                    }
                    for url in task['urls']
                ]
            }
            
            # 更新任务状态为完成
            storage.update_task(task_id, {
                'status': TaskStatus.COMPLETED.value,
                'result': result,
                'updated_at': datetime.utcnow().isoformat()
            })
            
            # 记录完成日志
            storage.add_log({
                'message': f'任务完成: {task["name"]} - 处理了 {len(task["urls"])} 个URL',
                'task_id': task_id,
                'level': 'info'
            })
            
        except Exception as e:
            # 如果出错，标记为失败
            storage.update_task(task_id, {
                'status': TaskStatus.FAILED.value,
                'error_message': str(e),
                'updated_at': datetime.utcnow().isoformat()
            })
            
            storage.add_log({
                'message': f'任务失败: {task["name"]} - {str(e)}',
                'task_id': task_id,
                'level': 'error'
            })
